﻿using System;
using Cysharp.Threading.Tasks;
using YooAsset;

namespace UniFramework.Asset
{
	public class DevAssetSystem : BaseAssetSystem
	{
		public override async UniTask Init(string defaultPackageName, Action initFinishCallBack)
		{
			await base.Init(defaultPackageName, initFinishCallBack);

			var buildResult = EditorSimulateModeHelper.SimulateBuild("DefaultPackage");
			var packageRoot = buildResult.PackageRootDirectory;
			var fileSystemParams = FileSystemParameters.CreateDefaultEditorFileSystemParameters(packageRoot);
			var createParameters = new EditorSimulateModeParameters();
			createParameters.EditorFileSystemParameters = fileSystemParams;
			var initOperation = _defaultPackage.InitializeAsync(createParameters);
			await initOperation;
			if (initOperation.Status != EOperationStatus.Succeed)
			{
				UniLogger.Error("DevAssetSystem Init Failed");
			}
			else
			{
				await RequestPackageVersion();
				await UpdatePackageManifest();
				initFinishCallBack?.Invoke();
				UniLogger.Log("DevAssetSystem Init Success");
			}
		}

		protected override async UniTask RequestPackageVersion()
		{
			var package = _defaultPackage;
			var operation = package.RequestPackageVersionAsync();
			await operation;
			if (operation.Status != EOperationStatus.Succeed)
			{
				UniLogger.Error("DevAssetSystem RequestPackageVersion Failed");
			}
			else
			{
				packageVersion = operation.PackageVersion;
				UniLogger.Log("DevAssetSystem RequestPackageVersion Success");
			}
		}

		protected override async UniTask UpdatePackageManifest()
		{
			var package = _defaultPackage;
			var operation = package.UpdatePackageManifestAsync(packageVersion);
			await operation;
			if (operation.Status != EOperationStatus.Succeed)
			{
				UniLogger.Error("DevAssetSystem UpdatePackageManifest Failed");
			}
			else
			{
				UniLogger.Log("DevAssetSystem UpdatePackageManifest Success");
			}
		}

		public override void Dispose()
		{
			_defaultPackage?.DestroyAsync();
			UniLogger.Log("DevAssetSystem Dispose Success");
		}
	}
}